package sword.chapter11BinarySearch;

/**
 * 狒狒吃香蕉
 *
 * @author K
 * @date 2021-12-26 18:12
 */
public class S73MinEatingSpeed {

    /**
     * @param piles 香蕉堆
     * @param H     回来时间
     */
    public static int s73(int[] piles, int H) {
        int right = 0;
        for (int pile : piles) {
            right = Math.max(pile, right);
        }

        int left = 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            int hours = getHours(piles, mid);
            if (hours <= H) {
                // 能在H内吃完
                if (mid == 1 || getHours(piles, mid - 1) > H) {
                    // 少吃一根，不能在H内吃完
                    return mid;
                }
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    public static int getHours(int[] piles, int speed) {
        int hours = 0;
        for (int pile : piles) {
            // 类似计算分页总页数 (total + pageSize - 1) / pageSize;
            hours += (pile + speed - 1) / speed;
        }
        return hours;
    }

    public static void main(String[] args) {
        int[] piles = {3, 6, 7, 11};
        int H = 8;
        int result = s73(piles, H);
        System.out.println();
    }
}
